package edu.whu.xterm.db;

import java.util.HashMap;
import java.util.Map;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import edu.whu.xterm.db.XTerm.FavoriteColumns;
import edu.whu.xterm.db.XTerm.Top10Columns;

public class XTermProvider extends ContentProvider {

	public static final String DB_NAME = "xterm.db";
	private static final int DB_VERSION = 1;

	public static final String TABLE_TOP10 = "top10";
	public static final String TABLE_FAVORITE = "favorite";

	private static final Map<String, String> sTop10ProjectionMap;

	private static final Map<String, String> sFavoriteProjectionMap;

	private static final UriMatcher sUriMatcher;

	private static final int TOP10 = 1;

	private static final int FAVORITE = 2;

	private SQLiteOpenHelper mOpenHelper;

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
			String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		switch (sUriMatcher.match(uri)) {
		case TOP10:
			qb.setTables(TABLE_TOP10);
			qb.setProjectionMap(sTop10ProjectionMap);
			break;
		case FAVORITE:
			qb.setTables(TABLE_FAVORITE);
			qb.setProjectionMap(sFavoriteProjectionMap);
			break;
		default:
			throw new IllegalArgumentException("Unkonwn URI " + uri);
		}
		final String orderBy = TextUtils.isEmpty(sortOrder) ? "" : sortOrder;
		final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		String table = "";
		Uri rUri = null;
		switch (sUriMatcher.match(uri)) {
		case TOP10:
			table = TABLE_TOP10;
			rUri = Top10Columns.CONTENT_URI;
			break;
		case FAVORITE:
			table = TABLE_FAVORITE;
			rUri = Top10Columns.CONTENT_URI;
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		final long rowId = db.insert(table, null, values);
		if (rowId > 0) {
			rUri = ContentUris.withAppendedId(rUri, rowId);
			getContext().getContentResolver().notifyChange(rUri, null);
			return rUri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int id = 0;
		switch (sUriMatcher.match(uri)) {
		case TOP10:
			id = db.delete(TABLE_TOP10, selection, selectionArgs);
			break;
		case FAVORITE:
			id = db.delete(TABLE_FAVORITE, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return id;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		return 0;
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + TABLE_TOP10 + " (" + Top10Columns._ID
					+ " INTEGER PRIMARY KEY," + Top10Columns.AUTHOR + " TEXT," + Top10Columns.TITLE
					+ " TEXT," + Top10Columns.BOARD_URL + " TEXT," + Top10Columns.TOPIC_AND_RE_URL
					+ " TEXT," + Top10Columns.AUTHOR_URL + " TEXT," + Top10Columns.BOARD + " TEXT"
					+ ");");
			db.execSQL("CREATE TABLE " + TABLE_FAVORITE + " (" + FavoriteColumns._ID
					+ " INTEGER PRIMARY KEY," + FavoriteColumns.IS_FAV_GROUP + " INTEGER,"
					+ FavoriteColumns.IS_GROUP + " INTEGER," + FavoriteColumns.BID + " INTEGER,"
					+ FavoriteColumns.NAME + " TEXT," + FavoriteColumns.ARTICLE_NUM + " INTEGER,"
					+ FavoriteColumns.POSITION + " INTEGER," + FavoriteColumns.DESC + " TEXT"
					+ ");");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			if (newVersion > oldVersion) {
				db.execSQL("DROP TABLE IF EXISTS " + TABLE_TOP10 + ";");
				db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITE + ";");
				onCreate(db);
			}
		}

	}

	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(XTerm.AUTHORITY, "top10", TOP10);
		sUriMatcher.addURI(XTerm.AUTHORITY, "favorite", FAVORITE);

		sTop10ProjectionMap = new HashMap<String, String>();
		sTop10ProjectionMap.put(Top10Columns._ID, Top10Columns._ID);
		sTop10ProjectionMap.put(Top10Columns.AUTHOR, Top10Columns.AUTHOR);
		sTop10ProjectionMap.put(Top10Columns.TITLE, Top10Columns.TITLE);
		sTop10ProjectionMap.put(Top10Columns.BOARD_URL, Top10Columns.BOARD_URL);
		sTop10ProjectionMap.put(Top10Columns.TOPIC_AND_RE_URL, Top10Columns.TOPIC_AND_RE_URL);
		sTop10ProjectionMap.put(Top10Columns.AUTHOR_URL, Top10Columns.AUTHOR_URL);
		sTop10ProjectionMap.put(Top10Columns.BOARD, Top10Columns.BOARD);

		sFavoriteProjectionMap = new HashMap<String, String>();
		sFavoriteProjectionMap.put(FavoriteColumns._ID, FavoriteColumns._ID);
		sFavoriteProjectionMap.put(FavoriteColumns.IS_GROUP, FavoriteColumns.IS_GROUP);
		sFavoriteProjectionMap.put(FavoriteColumns.IS_FAV_GROUP, FavoriteColumns.IS_FAV_GROUP);
		sFavoriteProjectionMap.put(FavoriteColumns.NAME, FavoriteColumns.NAME);
		sFavoriteProjectionMap.put(FavoriteColumns.DESC, FavoriteColumns.DESC);
		sFavoriteProjectionMap.put(FavoriteColumns.ARTICLE_NUM, FavoriteColumns.ARTICLE_NUM);
		sFavoriteProjectionMap.put(FavoriteColumns.POSITION, FavoriteColumns.POSITION);
		sFavoriteProjectionMap.put(FavoriteColumns.BID, FavoriteColumns.BID);
	}

}
